package com.seu.me.zookeeper.zkclient.base;

import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.ZkConnection;

import java.util.List;

/**
 * ZkClient对原生API进行了封装
 * 内部实现了Session超时重连，Watcher反复注册等功能。
 * 像dubbo等框架对其也进行了集成使用。
 * <p>
 * zkClient目前已经运用到了很多项目中，知名的有Dubbo、Kafka、Helix。
 *
 * @author liangfeihu
 * @since 2017/12/5 17:26.
 */
public class ZkClientBase {
    /**
     * zookeeper地址
     */
    static final String CONNECT_ADDR = "192.168.169.129:2181,192.168.169.130:2181,192.168.169.131:2181";
    /**
     * session超时时间 ms
     */
    static final int SESSION_TIMEOUT = 5000;

    /**
     * main 测试
     *
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        ZkClient zkc = new ZkClient(new ZkConnection(CONNECT_ADDR), SESSION_TIMEOUT);
        //1. create and delete方法
        zkc.createEphemeral("/temp");
        zkc.createPersistent("/super2/c2", true);
        Thread.sleep(10000);
        zkc.delete("/temp");
        zkc.deleteRecursive("/super2");

        //2. 设置path和data 并且读取子节点和每个节点的内容
        zkc.createPersistent("/super1", "1234");
        zkc.createPersistent("/super1/c1", "c1内容");
        zkc.createPersistent("/super1/c2", "c2内容");
        List<String> list = zkc.getChildren("/super1");
        for (String p : list) {
            System.out.println("path=" + p);
            String rp = "/super1/" + p;
            String data = zkc.readData(rp);
            System.out.println("节点为：" + rp + "，内容为: " + data);
        }

        //3. 更新和判断节点是否存在
        zkc.writeData("/super1/c1", "新内容");
        System.out.println(zkc.readData("/super1/c1") + "");
        System.out.println(zkc.exists("/super1/c1"));

        //4.递归删除/super内容
        zkc.deleteRecursive("/super1");
    }
}
